<script lang="ts">
import BookShelf from './book_shelf.vue'
import Loading from './loading.vue'

export default {
    data() {
        return {
            book_dict:new Map(),
            filter_word:'',
            is_loading:true,
        }
    },
    components:{
        shelf:BookShelf,
        loading:Loading,
    },
    methods:{
        async get_books(){
            this.is_loading=true
            const api='http://localhost:9999/books'
            let res=await fetch(api)
            if (res.ok) {
                let books=await res.json()
                console.log('Request books ok!')
                console.dir(books)
                this.book_dict.clear()
                books.forEach(book => {
                    this.book_dict.set(book.id,book)
                });
                // this.is_loading=false
            }else{
                let error=res.text()
                alert('Request books failed!\n'+error)
            }
        },
    },
    computed:{
        filtered_book_dict(){
            console.log('filter word changed:'+this.filter_word)
            if (this.filter_word) {
                let filtered_dict=new Map()
                for (let [key,book] of this.book_dict){
                    if (book.title.includes(this.filter_word)) {
                        filtered_dict.set(key,book)
                    }
                }
                return filtered_dict
            }else{
                return this.book_dict
            }
        }
    },
    mounted(){
        this.get_books()
    }
}
</script>

<template>
    <div class="library">
        <input type="text" v-model="filter_word" placeholder="漫画太多？检索一下！">
        <loading v-if="is_loading"></loading>
        <div v-else class="shelf-container">
            <shelf :collection="filtered_book_dict"></shelf>
        </div>
    </div>
</template>

<style lang="scss">
    .library{
        padding: 10px;
        display: flex;
        flex-direction: column;
        margin: 10px;
        height: calc(100vh - 20px);
        input{
            align-self: center;
            margin-bottom: 10px;
        }
        .shelf-container{
            height: calc(100% - 100px);
        }
    }
</style>
